package com.lykj.llw.box.ui.activity

import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import app.dinus.com.itemdecoration.GridDividerItemDecoration
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.component.GlideApp
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.PicAdapter
import com.lykj.llw.box.custom.imageload.GlideImageLoader
import com.lykj.llw.box.data.bean.response.RecyclingResponse
import com.lykj.llw.box.data.bean.response.SaleDetailDisplayResponse
import com.lykj.llw.box.data.bean.response.SaleRoleResponse
import com.lykj.llw.box.data.bean.response.UploadResponse
import com.lykj.llw.box.data.model.PicModel
import com.lykj.llw.box.databinding.ActSaleRoleDetailBinding
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.lzy.imagepicker.ui.ImageGridActivity
import com.lzy.imagepicker.view.CropImageView
import io.reactivex.disposables.Disposable
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException

/**
 * ================================================
 * 售卖角色详情
 * ================================================
 *
 * @author gosha
 * @date 2023/10/23-18:13
 */
class SaleRoleDetailActivity : BaseActivity() {
    lateinit var binding: ActSaleRoleDetailBinding

    private var mBean: SaleRoleResponse.DataDTO? = null

    private val pics = ArrayList<String>()
    private val mSelectedImages = ArrayList<ImageItem>()
    private val mAdapter = PicAdapter()
    private val mData = ArrayList<PicModel>()

    private val REQUEST_CODE_SELECT = 100
    private val mNormalAdd = PicModel(true, "", "", 0)
    private var uploadSequence = 0

    private var mTextWatcher: TextWatcher? = null

    private var id = 0
    private var pid = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActSaleRoleDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        super.onResume()

        ImmersionBar
            .with(this)
            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()
    }

    override fun initUI() {
        if (intent.getBooleanExtra("isEdit", false)) {
            id = intent.getIntExtra("id", 0)
            pid = intent.getIntExtra("pid", 0)
            obtainSaleDetail()
        } else {
            mBean = intent.getParcelableExtra("bean")

            //设置获取的属性
            binding.tvGameName.text = "${mBean?.gamename}"
            binding.tvRoleName.text = "${mBean?.rolename}"
            binding.tvChooseServer.text = "${mBean?.zonename}"

            GlideApp.with(this)
                .load(mBean?.gameIcon)
                .transition(DrawableTransitionOptions.withCrossFade())
                .into(binding.ivIcon)

            mData.add(mNormalAdd)
            mAdapter.notifyDataSetChanged()
        }

        binding.titleBar.tvTitle.text = "出售小号"
        binding.titleBar.tvRightOption.visibility = View.GONE

        initRCV()
    }

    private fun initRCV() {
        val gridLayoutManager = GridLayoutManager(this, 3)
        binding.rcvUpload.layoutManager = gridLayoutManager
        binding.rcvUpload.setHasFixedSize(true)

        val dividerItemDecoration = GridDividerItemDecoration(
            this,
            GridDividerItemDecoration.GRID_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setHorizontalDivider(
            resources.getDrawable(
                R.drawable.divider_15dp, resources.newTheme()
            )
        )
        dividerItemDecoration.setVerticalDivider(
            resources.getDrawable(
                R.drawable.divider_15dp, resources.newTheme()
            )
        )
        mAdapter.addChildClickViewIds(R.id.iv_add, R.id.iv_pic, R.id.iv_delete)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                R.id.iv_add -> {//添加
                    //打开选择,本次允许选择的数量
                    ImagePicker.getInstance().selectLimit = 5 - mSelectedImages.size
                    ImagePicker.getInstance().isMultiMode = true
//                    if (mSelectedImages.size > 0) {
//                        ImagePicker.getInstance().selectedImages = mSelectedImages
//                    }
                    val intent = Intent(
                        this@SaleRoleDetailActivity,
                        ImageGridActivity::class.java
                    )

                    startActivityForResult(
                        intent,
                        REQUEST_CODE_SELECT
                    )
                }

                R.id.iv_pic -> {//预览
                    val intent = Intent(this, ImageDisplayActivity::class.java)
                    intent.putExtra("pic", mAdapter.getItem(position).remoteUrl)
                    startActivity(intent)
                }

                R.id.iv_delete -> {//删除
                    mData.removeAt(position)
                    mSelectedImages.removeAt(position)
                    //判断是否存在添加项 存在不添加啊,不存在添加
                    var hasAdd = mData[mData.size - 1].itemType == 1

                    if (!hasAdd) {
                        mData.add(mNormalAdd)
                    }
                    mAdapter.notifyDataSetChanged()
                }
            }
        }
        binding.rcvUpload.addItemDecoration(dividerItemDecoration, 0)
        mAdapter.data = mData
        mAdapter.canDelete(false)
        binding.rcvUpload.adapter = mAdapter
    }

    //获取售卖详情
    private fun obtainSaleDetail() {
        RetrofitManager.instance.obtainSaleDetail(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@SaleRoleDetailActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(
                    responseBody,
                    SaleDetailDisplayResponse::class.java
                )

                //设置获取的属性
                binding.tvGameName.text = "${bean.data?.gameName}"
                binding.tvRoleName.text = "${bean.data?.rolename}"
                binding.tvChooseServer.text = "${bean.data?.zonename}"
                binding.etRemark.setText("${bean?.data?.userRemark}")
                binding.etSaleMoney.setText("${bean?.data?.money}")

                binding.etRemark.isEnabled = false
                binding.etSaleMoney.isEnabled = false
                binding.tvBtnSubmit.visibility = View.GONE

                GlideApp.with(this@SaleRoleDetailActivity)
                    .load(bean.data?.gameIcon)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(binding.ivIcon)

                bean.data.picList.forEach {
                    val picModel = PicModel(false, "", it, 0)
                    mData.add(picModel)
                }
                mAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@SaleRoleDetailActivity, msg)
                }
            }
        }, "$id")
    }

    //申请交易
    private fun applyTrading() {
        clearBodyParam()
        initBodyParam()
        bodyParams["money"] = binding.etSaleMoney.text.toString()
        bodyParams["partId"] = "${mBean?.partId ?: pid}"
        bodyParams["partLevel"] = "0"
        pics.clear()
        mData.forEach {
            if (it.remoteUrl.contains("http")) {
                pics.add(it.remoteUrl)
            }
        }
        bodyParams["pics"] = pics
        bodyParams["remark"] = "${binding.etRemark.text}"

        RetrofitManager.instance.applyTrading(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@SaleRoleDetailActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                ToastUtils.showShort(this@SaleRoleDetailActivity, "交易成功")
                finish()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@SaleRoleDetailActivity, msg)
                }
            }
        }, bodyParams)
    }

    override fun initData() {
        initImagePicker()
    }

    private fun initImagePicker() {
        ImagePicker.getInstance().apply {
            imageLoader = GlideImageLoader() //设置图片加载器
            isShowCamera = true //显示拍照按钮
            isCrop = false //允许裁剪（单选才有效）
            isSaveRectangle = true //是否按矩形区域保存
            selectLimit = 5 //选中数量限制
            style = CropImageView.Style.RECTANGLE //裁剪框的形状
            focusWidth = 800 //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
            focusHeight = 800 //裁剪框的高度。单位像素（圆形自动取宽高最小值）
            outPutX = 1000 //保存文件的宽度。单位像素
            outPutY = 1000
        }
    }

    override fun setListener() {
        binding.titleBar.ivBack.clickWithTrigger {
            finish()
        }

        mTextWatcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }

            override fun afterTextChanged(s: Editable?) {
                if (s?.toString()?.length == 1 && s.toString() == "0") {
                    s.delete(0, 1)
                }
            }
        }
        binding.etSaleMoney.addTextChangedListener(mTextWatcher)

        binding.tvBtnSubmit.clickWithTrigger {
            if (binding.etSaleMoney.text.isNullOrBlank()) {
                ToastUtils.showShort(this@SaleRoleDetailActivity, "请输入金额")
                return@clickWithTrigger
            }
            //FIXME:最低出售价格
            if (binding.etSaleMoney.text.toString().toInt() < 6) {
                ToastUtils.showShort(this@SaleRoleDetailActivity, "最低6元出售")
                return@clickWithTrigger
            }
            if (mData.size == 0) {
                ToastUtils.showShort(this@SaleRoleDetailActivity, "请添加图片")
                return@clickWithTrigger
            } else {
                if (!judgeUploadComplete()) {
                    ToastUtils.showShort(this@SaleRoleDetailActivity, "等待图片上传完成")
                    return@clickWithTrigger
                }
            }

            applyTrading()
        }

        KeyboardUtils.registerSoftInputChangedListener(this) {
            if (it == 0) {
                binding.etRemark.clearFocus()
                binding.etSaleMoney.clearFocus()
            }
        }
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                val images =
                    data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>
                if (images != null) {
//                    uploadSequence++
                    LogUtils.e("选择图片返回:${images[0].uri}")
                    mSelectedImages.addAll(images)

                    mData.clear()
                    mSelectedImages.forEach {
                        val model = PicModel(
                            false,
                            getRealFilePath(this, it.uri)!!,
                            getRealFilePath(this, it.uri)!!,
                            uploadSequence
                        )
                        mData.add(model)
                    }

                    if (mSelectedImages.size < 5) {
                        mData.add(mNormalAdd)
                    }
                    mAdapter.notifyDataSetChanged()

                    //开始上传
                    uploadPicList()
                }
            }
        }
    }

    override fun onDestroy() {
        binding.etSaleMoney.removeTextChangedListener(mTextWatcher)
        removeDisposables(this)
        super.onDestroy()
    }

    /**
     * 上传图片集合
     */
    private fun uploadPicList() {
        for (index in mData.indices) {
            if (mData[index].itemType == 1) {
                continue
            }

            uploadPic(index, mData[index].remoteUrl)
        }
    }

    private fun uploadPic(index: Int, filePath: String) {
        RetrofitManager.instance
            .uploadSingleFile("http://hezi-api.66wsy.com/upload/files", filePath, "image/jpeg")
            .enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    LogUtils.e("上传图片失败")
                }

                override fun onResponse(call: Call, response: Response) {
                    try {
                        val str = response.body?.string()
                        val bean = GsonUtils.fromJson(str, UploadResponse::class.java)
                        mData[index].remoteUrl = bean.data

                        LogUtils.e("上传完的图片地址:${bean.data}")
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }
            })
    }

    //判断图片是否上传完成
    private fun judgeUploadComplete(): Boolean {
        var isComplete = true
        for (item in mData) {
            if (item.itemType == 1) {
                continue
            }
            if (!item.remoteUrl.contains("http")) {
                isComplete = false
                break
            }
        }
        return isComplete
    }

    /**
     * Uri转File
     */
    private fun getRealFilePath(context: Context, uri: Uri): String? {
        if (null == uri) {
            return null
        }
        val scheme: String = uri.scheme!!
        var data: String? = null
        if (scheme == null) {
            data = uri.path
        } else if (ContentResolver.SCHEME_FILE == scheme) {
            data = uri.path
        } else if (ContentResolver.SCHEME_CONTENT == scheme) {
            val cursor: Cursor? = context.contentResolver
                .query(uri, arrayOf(MediaStore.Images.ImageColumns.DATA), null, null, null)
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    val index: Int = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
                    if (index > -1) {
                        data = cursor.getString(index)
                    }
                }
                cursor.close()
            }
        }
        return data
    }
}